import React, { LegacyRef, useEffect, useRef, useState } from 'react';
import { Route, useRouteMatch } from 'react-router';
import { HotTable } from '@handsontable/react';
import 'handsontable/dist/handsontable.full.css';
import 'handsontable/languages/zh-CN';
import Handsontable from 'handsontable';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faFileUpload } from '@fortawesome/free-solid-svg-icons';
import { motion } from 'framer-motion';
import FormGroup from '@material-ui/core/FormGroup';
import FormHelperText from '@material-ui/core/FormHelperText';
import Checkbox from '@material-ui/core/Checkbox';
import { getCsvSheet, upload } from '@/utils/upload';
import cls from 'classnames';
import { omit } from 'lodash';

import styles from '../index.module.scss';
import {
  createStyles,
  InputLabel,
  makeStyles,
  MenuItem,
  Select,
  TextField,
  Theme,
  ThemeProvider,
  Typography,
  FormControl,
  FormControlLabel,
  Switch,
  FormLabel,
  Button,
} from '@material-ui/core';
import {
  AggregateFunction,
  DataTransformationFunction,
  DataTransformationL2,
  DataTransformationType,
  Generalization,
  GlobalPopulation,
  HierarchyDate,
  HierarchyMasking,
  HierarchyOrder,
  MapPopulationModel,
  PutPopulationModel,
  SearchStrategy,
  UtilityMeasure,
} from '@/constants/config';
import {
  addAllParameters,
  findAllParameters,
  getSourceFile,
  listTaskVersion,
} from '@/api';

const tabMap = {
  config: '任务配置',
  explore: '探索结果',
  analyze: '效用分析',
  risk: '风险分析',
};

const genEmptyData = () => [
  ['', '', ''],
  ['', '', ''],
];

let data = genEmptyData();

const emptySheet = data;

let attrSheetData: Record<string, string[][]> = {};

let attrSheetRef: Record<string, React.RefObject<HotTable | undefined>> = {};

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      '& .MuiFormControl-root': {
        marginRight: theme.spacing(1),
        width: '3em',
      },
    },
    formControl: {},
  })
);

function Configuration() {
  const classes = useStyles();

  const {
    params: { id, taskId, versionId },
    path,
  } = useRouteMatch<{ id: string; taskId: string; versionId: string }>();
  const [language, setLanguage] = useState('zh-CN');
  const [sourceData, setSourceData] = useState(data);
  const [curAttr, setCurAttr] = useState('');
  const hottable = useRef<HotTable>();
  const [tabs, setTabs] = useState<
    {
      key: string;
      label: string;
      checked: boolean;
      canRead: boolean;
    }[]
  >([]);
  const [attrConfig, setAttrConfig] = useState<
    Record<string, Record<string, any>>
  >({});
  const [privacyModel, setPrivacyModel] = useState<Record<string, any>>({});
  const [globalConfiguration, setGlobalConfiguration] = useState<
    Record<string, any>
  >({});

  useEffect(() => {
    // 在这里初始化
    if (id === 'init') {
      return;
    }
    (async () => {
      const { data: _data } = await findAllParameters(id);
      console.log('privacy', _data.privacyModel);
      setPrivacyModel(_data.privacyModel);
      setGlobalConfiguration(_data.globalConfiguration);
      setSourceData(_data.sourceSheet);
      data = _data.sourceSheet;
      hottable.current?.hotInstance.loadData(data);
      for (let attr of _data.attribute) {
        attrSheetData[attr.name] = attr.sheet;
        attrSheetRef[attr.name].current?.hotInstance.loadData(
          attrSheetData[attr.name]
        );
        updateAttr(
          attr.name,
          'sheet'
        )({ target: { value: attrSheetData[attr.name] } });
        setAttrConfig((pv) => ({
          ...pv,
          [attr.name]: {
            ...(pv[attr.name] ?? {}),
            ...attr.config,
            attributeConfigurationName: attr.name ?? '',
          },
        }));
      }

      console.log('data data', _data);
    })();
  }, [id, taskId]);

  useEffect(() => {
    console.log('attr config', attrConfig);
  }, [attrConfig]);

  useEffect(() => {
    console.log('source data', sourceData);
    const _tabs = sourceData[0].map((entry) => ({
      key: entry,
      label: entry,
      checked: false,
      canRead: false,
    }));
    if (!_tabs[0].key) {
      return;
    }
    setTabs(_tabs);
    setCurAttr(_tabs[0].key);
    attrSheetData = sourceData[0].reduce((acc, cur) => {
      acc[cur] = genEmptyData();
      return acc;
    }, {} as Record<string, string[][]>);
    for (let key of sourceData[0]) {
      attrSheetRef[key] = React.createRef();
    }
  }, [sourceData]);

  const updateAttr =
    (attr: string, key: string, type = 'normal') =>
    (e: UpdateAttrEvent<string>) => {
      const value = type === 'normal' ? e.target.value : e.target.checked;
      console.log(attr, key, type, value);
      if (value || value === false) {
        setAttrConfig((pv) => ({
          ...pv,
          [attr]: {
            ...(pv[attr] ?? {}),
            [key]: value as string,
            attributeConfigurationName: attr ?? '',
          },
        }));
      } else {
        delete attrConfig?.[attr]?.[key];
        setAttrConfig(Object.assign({}, attrConfig));
      }
    };

  const updatePrivacyModel =
    (key: string, type = 'normal') =>
    (e: UpdateAttrEvent<string>) => {
      const value = type === 'normal' ? e.target.value : e.target.checked;
      if (value || value === false) {
        setPrivacyModel((pv) => ({
          ...pv,
          [key]: value,
        }));
      } else {
        delete privacyModel?.[key];
        setPrivacyModel(Object.assign({}, privacyModel));
      }
    };

  useEffect(() => {
    console.log('privacy', privacyModel);
  }, [privacyModel]);

  const updateGlobalConfiguration =
    (key: string, type = 'normal') =>
    (e: UpdateAttrEvent<string>) => {
      const value = type === 'normal' ? e.target.value : e.target.checked;
      if (value || value === false) {
        setGlobalConfiguration((pv) => ({
          ...pv,
          [key]: value,
        }));
      } else {
        delete privacyModel?.[key];
        setGlobalConfiguration(Object.assign({}, globalConfiguration));
      }
    };

  const handlePrivacyModelChange = (event: {
    target: { name: string; checked: boolean };
  }) => {
    if (event.target.checked) {
      setPrivacyModel((prev) => ({
        ...prev,
        privacyModelName: (prev?.privacyModelName ?? []).concat(
          event.target.name
        ),
      }));
    } else {
      setPrivacyModel((prev) => ({
        ...prev,
        privacyModelName: (prev?.privacyModelName ?? []).filter(
          (item: string) => item !== event.target.name
        ),
      }));
    }
  };

  function submitInput() {
    console.log('this is result', {
      sourceData,
      attrConfig,
      privacyModel,
      globalConfiguration,
    });

    const result = {
      sourceSheet: sourceData,
      attribute: Object.values(attrConfig).map((item) => ({
        name: item.attributeConfigurationName as string,
        sheet: item.sheet as string[][],
        config: {
          ...omit(item, ['sheet']),
        },
      })),
      privacyModel,
      globalConfiguration,
      taskUuid: taskId,
      versionUuid: versionId,
    };

    console.log('final result', result);
    addAllParameters(result);
  }

  return (
    <div>
      <h1>
        匿名化数据
        <FontAwesomeIcon
          icon={faFileUpload}
          style={{ marginLeft: 15 }}
          onClick={async () => {
            const file = await getCsvSheet();
            console.log(file);
            data = file;
            hottable.current?.hotInstance.loadData(data);
            setSourceData(data);
          }}
        />
      </h1>
      <HotTable
        ref={hottable as LegacyRef<HotTable>}
        language={language}
        data={data}
        licenseKey="non-commercial-and-evaluation"
        contextMenu={true}
        afterContextMenuHide={(e) => {
          setSourceData([...data]);
        }}
        beforeChangeRender={(e) => {
          setSourceData([...data]);
        }}
      />
      <h1>参数配置</h1>
      <div>
        <ul className={styles['task-tab']}>
          {tabs.map(({ key, label, checked, canRead }) => (
            <motion.li
              aria-disabled
              key={key}
              className={cls(
                styles['task-tab-item'],
                attrConfig[key] ? styles['active'] : styles['inactive']
              )}
              whileHover={{
                skewX: 2,
                backgroundColor: '#90a3bb',
                color: '#000000',
              }}
              onClick={() => {
                setCurAttr(key);
              }}
              animate={
                curAttr === key
                  ? {
                      skewX: 2,
                      backgroundColor: '#90a3bb',
                      color: '#000000',
                    }
                  : {
                      skewX: 0,
                      backgroundColor: '#424b56',
                      color: '#c1c6cb',
                    }
              }
            >
              {label}
            </motion.li>
          ))}
        </ul>
      </div>
      <div>
        {tabs.map(({ key }) => {
          return key === curAttr ? (
            <div
              style={{ opacity: key === curAttr ? 1 : 0 }}
              className={styles['attribute-panel']}
            >
              <FontAwesomeIcon
                icon={faFileUpload}
                style={{ marginLeft: 15, fontSize: '2rem' }}
                onClick={async () => {
                  const file = await getCsvSheet();
                  attrSheetData[key] = file;
                  attrSheetRef[key].current?.hotInstance.loadData(
                    attrSheetData[key]
                  );
                  updateAttr(
                    key,
                    'sheet'
                  )({ target: { value: attrSheetData[key] } });
                }}
              />
              <HotTable
                ref={attrSheetRef[key] as LegacyRef<HotTable>}
                language={language}
                data={attrSheetData[key]}
                licenseKey="non-commercial-and-evaluation"
                contextMenu={true}
                afterContextMenuHide={(e) => {
                  // setSourceData([...data]);

                  updateAttr(
                    key,
                    'sheet'
                  )({ target: { value: attrSheetData[key] } });
                }}
                beforeChangeRender={(e) => {
                  // setSourceData([...data]);
                  console.log('sheet', attrSheetData);
                  updateAttr(
                    key,
                    'sheet'
                  )({ target: { value: attrSheetData[key] } });
                }}
              />
              <Typography variant="h5" component="h2" style={{ marginTop: 30 }}>
                Attribute metadata
              </Typography>
              <div className={classes.root}>
                <FormControl>
                  <InputLabel>Data type</InputLabel>
                  <Select
                    label="Data type"
                    value={attrConfig?.[key]?.['dataType'] ?? ''}
                    onChange={updateAttr(key, 'dataType')}
                  >
                    {[
                      'Date',
                      'Decimal',
                      'Integer',
                      'String',
                      'Ordered String',
                    ].map((k) => (
                      <MenuItem value={k}>{k}</MenuItem>
                    ))}
                  </Select>
                </FormControl>
                <FormControl>
                  <FormLabel>Target variable</FormLabel>
                  <Switch
                    checked={
                      (attrConfig?.[key]?.['targetVariable'] as boolean) ??
                      false
                    }
                    onChange={updateAttr(key, 'targetVariable', 'switch')}
                  />
                </FormControl>
              </div>
              <Typography variant="h5" component="h2">
                Create a generalization hierarchy
              </Typography>
              <div className={classes.root}>
                <FormControl>
                  <InputLabel>Hierarchy</InputLabel>
                  <Select
                    value={attrConfig?.[key]?.['hierarchyChoice'] ?? ''}
                    onChange={updateAttr(key, 'hierarchyChoice')}
                  >
                    {[
                      'None',
                      'ForDates',
                      'Interval',
                      'Ordering',
                      'Masking',
                    ].map((k) => (
                      <MenuItem value={k}>{k}</MenuItem>
                    ))}
                  </Select>
                </FormControl>
                {attrConfig?.[key]?.['hierarchyChoice'] === 'ForDates' &&
                  attrConfig?.[key]?.['dataType'] === 'Date' && (
                    <FormControl>
                      <InputLabel>Date</InputLabel>
                      <Select
                        value={attrConfig?.[key]?.['num'] ?? ''}
                        onChange={updateAttr(key, 'num')}
                      >
                        {HierarchyDate.map((k) => (
                          <MenuItem value={k}>{k}</MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  )}
                {attrConfig?.[key]?.['hierarchyChoice'] === 'Interval' &&
                  ['Decimal', 'Integer', 'Ordered String'].includes(
                    attrConfig?.[key]?.['dataType']
                  ) && (
                    <div>
                      <Typography variant="h6" component="h2">
                        Lower bound:
                      </Typography>
                      <TextField
                        value={attrConfig?.[key]?.['bottomSnapFrom'] ?? ''}
                        onChange={updateAttr(key, 'bottomSnapFrom')}
                        required
                        label="Bottom snap from"
                        type="number"
                      />
                      <TextField
                        value={attrConfig?.[key]?.['bottomCodingFrom'] ?? ''}
                        onChange={updateAttr(key, 'bottomCodingFrom')}
                        required
                        label="Bottom coding from"
                        type="number"
                      />
                      <TextField
                        value={attrConfig?.[key]?.['minFrom'] ?? ''}
                        onChange={updateAttr(key, 'minFrom')}
                        required
                        label="Minimum value"
                        type="number"
                      />
                      <Typography variant="h6" component="h2">
                        Upper bound:
                      </Typography>
                      <TextField
                        value={attrConfig?.[key]?.['topSnapFrom'] ?? ''}
                        onChange={updateAttr(key, 'topSnapFrom')}
                        required
                        label="Top snap from"
                        type="number"
                      />
                      <TextField
                        value={attrConfig?.[key]?.['topCodingFrom'] ?? ''}
                        onChange={updateAttr(key, 'topCodingFrom')}
                        required
                        label="Top coding from"
                        type="number"
                      />
                      <TextField
                        value={attrConfig?.[key]?.['maxFrom'] ?? ''}
                        onChange={updateAttr(key, 'maxFrom')}
                        required
                        label="Maximum value"
                        type="number"
                      />
                    </div>
                  )}
                {attrConfig?.[key]?.['hierarchyChoice'] === 'Ordering' && (
                  <FormControl>
                    <InputLabel>Order</InputLabel>
                    <Select
                      value={attrConfig?.[key]?.['orderDataType'] ?? ''}
                      onChange={updateAttr(key, 'orderDataType')}
                    >
                      {HierarchyOrder.map((k) => (
                        <MenuItem value={k}>{k}</MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                )}
                {attrConfig?.[key]?.['hierarchyChoice'] === 'Masking' && (
                  <>
                    <FormControl>
                      <InputLabel>Alignment</InputLabel>
                      <Select
                        value={attrConfig?.[key]?.['alignment'] ?? ''}
                        onChange={updateAttr(key, 'alignment')}
                      >
                        {HierarchyMasking.map((k) => (
                          <MenuItem value={k}>{k}</MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                    <FormControl>
                      <InputLabel>Masking</InputLabel>
                      <Select
                        value={attrConfig?.[key]?.['masking'] ?? ''}
                        onChange={updateAttr(key, 'masking')}
                      >
                        {HierarchyMasking.map((k) => (
                          <MenuItem value={k}>{k}</MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  </>
                )}
              </div>
              <Typography variant="h5" component="h2">
                Data transformation
              </Typography>
              <div className={classes.root}>
                <FormControl>
                  <InputLabel>Type</InputLabel>
                  <Select
                    value={attrConfig?.[key]?.['typeName'] ?? ''}
                    onChange={updateAttr(key, 'typeName')}
                  >
                    {DataTransformationType.map((k) => (
                      <MenuItem value={k}>{k}</MenuItem>
                    ))}
                  </Select>
                </FormControl>
                <FormControl>
                  <InputLabel>Transformation</InputLabel>
                  <Select
                    value={attrConfig?.[key]?.['transformation'] ?? ''}
                    onChange={updateAttr(key, 'transformation')}
                  >
                    {DataTransformationL2.map((k) => (
                      <MenuItem value={k}>{k}</MenuItem>
                    ))}
                  </Select>
                </FormControl>
                {attrConfig?.[key]?.['transformation'] === 'Generalization' && (
                  <>
                    {' '}
                    <TextField
                      value={attrConfig?.[key]?.['minimum'] ?? ''}
                      onChange={updateAttr(key, 'minimum')}
                      required
                      label="Minimum"
                      type="number"
                    />
                    <TextField
                      value={attrConfig?.[key]?.['maximum'] ?? ''}
                      onChange={updateAttr(key, 'maximum')}
                      required
                      label="Maximum"
                      type="number"
                    />
                  </>
                )}
                {(attrConfig?.[key]?.['transformation'] ===
                  'MicroAggregation' ||
                  attrConfig?.[key]?.['transformation'] ===
                    'Clustering and microaggregation') && (
                  <FormControl>
                    <InputLabel>Function</InputLabel>
                    <Select
                      value={attrConfig?.[key]?.['functionName'] ?? ''}
                      onChange={updateAttr(key, 'functionName')}
                    >
                      {DataTransformationFunction.map((k) => (
                        <MenuItem value={k}>{k}</MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                )}
                <TextField
                  value={attrConfig?.[key]?.['weight'] ?? ''}
                  onChange={updateAttr(key, 'weight')}
                  required
                  label="Attribute weight"
                  type="number"
                />
              </div>
            </div>
          ) : (
            <div></div>
          );
        })}
      </div>
      <div className={styles['attribute-panel']}>
        <Typography variant="h5" component="h2" style={{ marginBottom: 5 }}>
          隐私模型
        </Typography>
        <div className={classes.root}>
          <FormLabel component="legend">选择你的隐私模型</FormLabel>
          <FormGroup row>
            <FormControlLabel
              control={
                <Checkbox
                  checked={
                    privacyModel?.['privacyModelName']?.includes(
                      'DifferentPrivacy'
                    ) ?? false
                  }
                  onChange={handlePrivacyModelChange}
                  name="DifferentPrivacy"
                />
              }
              label="Different Privacy"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={
                    privacyModel?.['privacyModelName']?.includes(
                      'KAnonymity'
                    ) ?? false
                  }
                  onChange={handlePrivacyModelChange}
                  name="KAnonymity"
                />
              }
              label="Kanonymity"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={
                    privacyModel?.['privacyModelName']?.includes('KMap') ??
                    false
                  }
                  onChange={handlePrivacyModelChange}
                  name="KMap"
                />
              }
              label="KMap"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={
                    privacyModel?.['privacyModelName']?.includes('Presence') ??
                    false
                  }
                  onChange={handlePrivacyModelChange}
                  name="Presence"
                />
              }
              label="Presence"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={
                    privacyModel?.['privacyModelName']?.includes(
                      'Profitability'
                    ) ?? false
                  }
                  onChange={handlePrivacyModelChange}
                  name="Profitability"
                />
              }
              label="Profitability"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={
                    privacyModel?.['privacyModelName']?.includes('Diversity') ??
                    false
                  }
                  onChange={handlePrivacyModelChange}
                  name="Diversity"
                />
              }
              label="Diversity"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={
                    privacyModel?.['privacyModelName']?.includes(
                      'TCloseness'
                    ) ?? false
                  }
                  onChange={handlePrivacyModelChange}
                  name="TCloseness"
                />
              }
              label="TCloseness"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={
                    privacyModel?.['privacyModelName']?.includes(
                      'Disclosure'
                    ) ?? false
                  }
                  onChange={handlePrivacyModelChange}
                  name="Disclosure"
                />
              }
              label="Disclosure"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={
                    privacyModel?.['privacyModelName']?.includes('Likeness') ??
                    false
                  }
                  onChange={handlePrivacyModelChange}
                  name="Likeness"
                />
              }
              label="Likeness"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={
                    privacyModel?.['privacyModelName']?.includes(
                      'AverageReidentificationRisk'
                    ) ?? false
                  }
                  onChange={handlePrivacyModelChange}
                  name="AverageReidentificationRisk"
                />
              }
              label="AverageReidentificationRisk"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={
                    privacyModel?.['privacyModelName']?.includes(
                      'PopulationUniqueness'
                    ) ?? false
                  }
                  onChange={handlePrivacyModelChange}
                  name="PopulationUniqueness"
                />
              }
              label="PopulationUniqueness"
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={
                    privacyModel?.['privacyModelName']?.includes(
                      'SampleUniqueness'
                    ) ?? false
                  }
                  onChange={handlePrivacyModelChange}
                  name="SampleUniqueness"
                />
              }
              label="SampleUniqueness"
            />
          </FormGroup>
          {privacyModel?.['privacyModelName']?.includes('DifferentPrivacy') && (
            <>
              <TextField
                value={privacyModel?.['delta'] ?? ''}
                onChange={updatePrivacyModel('delta')}
                required
                label="Delta"
                type="number"
              />
              <TextField
                value={privacyModel?.['epsilon'] ?? ''}
                onChange={updatePrivacyModel('epsilon')}
                required
                label="Epsilon"
                type="number"
              />
              <FormControl>
                <InputLabel>Generalization</InputLabel>
                <Select
                  value={privacyModel?.['generalization'] ?? ''}
                  onChange={updatePrivacyModel('generalization')}
                >
                  {Generalization.map((k) => (
                    <MenuItem value={k}>{k}</MenuItem>
                  ))}
                </Select>
              </FormControl>
              <FormControl>
                <FormLabel>Can Enable</FormLabel>
                <Switch
                  checked={
                    (privacyModel?.['ddeterministic'] as boolean) ?? false
                  }
                  onChange={updatePrivacyModel('ddeterministic', 'switch')}
                />
              </FormControl>
            </>
          )}
          {privacyModel?.['privacyModelName']?.includes('KAnonymity') && (
            <>
              <TextField
                value={privacyModel?.['kanonymityValue'] ?? ''}
                onChange={updatePrivacyModel('kanonymityValue')}
                required
                label="Kanonymity Value"
                type="number"
              />
            </>
          )}
          {privacyModel?.['privacyModelName']?.includes('KMap') && (
            <>
              <TextField
                value={privacyModel?.['kmapValue'] ?? ''}
                onChange={updatePrivacyModel('kmapValue')}
                required
                label="KMap Value"
                type="number"
              />
              <TextField
                value={privacyModel?.['significancelLevel'] ?? ''}
                onChange={updatePrivacyModel('significancelLevel')}
                required
                label="Significancel Level"
                type="number"
              />
              <FormControl>
                <InputLabel>Map Population Model</InputLabel>
                <Select
                  value={privacyModel?.['mapPopulationModel'] ?? ''}
                  onChange={updatePrivacyModel('mapPopulationModel')}
                >
                  {MapPopulationModel.map((k) => (
                    <MenuItem value={k}>{k}</MenuItem>
                  ))}
                </Select>
              </FormControl>
            </>
          )}
          {privacyModel?.['privacyModelName']?.includes('Presence') && (
            <>
              <TextField
                value={privacyModel?.['dmin'] ?? ''}
                onChange={updatePrivacyModel('dmin')}
                required
                label="Dmin"
                type="number"
              />
              <TextField
                value={privacyModel?.['dmax'] ?? ''}
                onChange={updatePrivacyModel('dmax')}
                required
                label="Dmax"
                type="number"
              />
            </>
          )}
          {privacyModel?.['privacyModelName']?.includes('Diversity') && (
            <>
              <TextField
                value={privacyModel?.['dvalue'] ?? ''}
                onChange={updatePrivacyModel('dvalue')}
                required
                label="Dvalue"
                type="number"
              />
            </>
          )}
          {privacyModel?.['privacyModelName']?.includes('Likeness') && (
            <>
              <TextField
                value={privacyModel?.['bvalue'] ?? ''}
                onChange={updatePrivacyModel('bvalue')}
                required
                label="Bvalue"
                type="number"
              />
            </>
          )}
          {privacyModel?.['privacyModelName']?.includes(
            'AverageReidentificationRisk'
          ) && (
            <>
              <TextField
                value={privacyModel?.['arrThreshold'] ?? ''}
                onChange={updatePrivacyModel('arrThreshold')}
                required
                label="Arr Threshold"
                type="number"
              />
            </>
          )}
          {privacyModel?.['privacyModelName']?.includes(
            'PopulationUniqueness'
          ) && (
            <>
              <TextField
                value={privacyModel?.['putThreshold'] ?? ''}
                onChange={updatePrivacyModel('putThreshold')}
                required
                label="Put Threshold"
                type="number"
              />
              <FormControl>
                <InputLabel>Put Population Model</InputLabel>
                <Select
                  value={privacyModel?.['putPopulationModel'] ?? ''}
                  onChange={updatePrivacyModel('putPopulationModel')}
                >
                  {PutPopulationModel.map((k) => (
                    <MenuItem value={k}>{k}</MenuItem>
                  ))}
                </Select>
              </FormControl>
            </>
          )}
          {privacyModel?.['privacyModelName']?.includes('SampleUniqueness') && (
            <>
              <TextField
                value={privacyModel?.['sutTHreshold'] ?? ''}
                onChange={updatePrivacyModel('sutTHreshold')}
                required
                label="Sut Threshold"
                type="number"
              />
            </>
          )}
        </div>
      </div>
      <div className={styles['attribute-panel']}>
        <Typography variant="h5" component="h2" style={{ marginBottom: 5 }}>
          全局配置
        </Typography>
        <div className={classes.root}>
          <FormControl>
            <InputLabel>Global Population</InputLabel>
            <Select
              label="Global Population"
              value={globalConfiguration['globalPopulation'] ?? ''}
              onChange={updateGlobalConfiguration('globalPopulation')}
            >
              {GlobalPopulation.map((k) => (
                <MenuItem value={k}>{k}</MenuItem>
              ))}
            </Select>
          </FormControl>
          <TextField
            value={globalConfiguration['publisherBenefit'] ?? ''}
            onChange={updateGlobalConfiguration('publisherBenefit')}
            required
            label="Publisher Benefit"
            type="number"
          />
          <TextField
            value={globalConfiguration['publisherLoss'] ?? ''}
            onChange={updateGlobalConfiguration('publisherLoss')}
            required
            label="Publisher Loss"
            type="number"
          />
          <TextField
            value={globalConfiguration['adversaryCost'] ?? ''}
            onChange={updateGlobalConfiguration('adversaryCost')}
            required
            label="Adversary Cost"
            type="number"
          />
          <TextField
            value={globalConfiguration['adversaryGain'] ?? ''}
            onChange={updateGlobalConfiguration('adversaryGain')}
            required
            label="Adversary Gain"
            type="number"
          />
          <TextField
            value={globalConfiguration['suppressionLimit'] ?? ''}
            onChange={updateGlobalConfiguration('suppressionLimit')}
            required
            label="Suppression Limit"
            type="number"
          />
          <FormControl>
            <FormLabel>Can Enable</FormLabel>
            <Switch
              checked={(globalConfiguration['canEnable'] as boolean) ?? false}
              onChange={updateGlobalConfiguration('canEnable', 'switch')}
            />
          </FormControl>
          <FormControl>
            <InputLabel>Utility Measure</InputLabel>
            <Select
              label="Utility Measure"
              value={globalConfiguration['utilityMeasure'] ?? ''}
              onChange={updateGlobalConfiguration('utilityMeasure')}
            >
              {UtilityMeasure.map((k) => (
                <MenuItem value={k}>{k}</MenuItem>
              ))}
            </Select>
          </FormControl>
          <FormControl>
            <FormLabel>Can Practical Monotonicity</FormLabel>
            <Switch
              checked={
                (globalConfiguration['canPracticalMonotonicity'] as boolean) ??
                false
              }
              onChange={updateGlobalConfiguration(
                'canPracticalMonotonicity',
                'switch'
              )}
            />
          </FormControl>
          <FormControl>
            <FormLabel>Can Journalist</FormLabel>
            <Switch
              checked={
                (globalConfiguration['canJournalist'] as boolean) ?? false
              }
              onChange={updateGlobalConfiguration('canJournalist', 'switch')}
            />
          </FormControl>
          <FormControl>
            <InputLabel>Aggregate Function</InputLabel>
            <Select
              label="Aggregate Function"
              value={globalConfiguration['aggregateFunction'] ?? ''}
              onChange={updateGlobalConfiguration('aggregateFunction')}
            >
              {AggregateFunction.map((k) => (
                <MenuItem value={k}>{k}</MenuItem>
              ))}
            </Select>
          </FormControl>
          <FormControl>
            <FormLabel>Can Search Strategy</FormLabel>
            <Switch
              checked={
                (globalConfiguration['canSearchStrategy'] as boolean) ?? false
              }
              onChange={updateGlobalConfiguration(
                'canSearchStrategy',
                'switch'
              )}
            />
          </FormControl>
          {globalConfiguration['canSearchStrategy'] && (
            <>
              <FormControl>
                <InputLabel>Search Strategy</InputLabel>
                <Select
                  label="Search Strategy"
                  value={globalConfiguration['searchStrategy'] ?? ''}
                  onChange={updateGlobalConfiguration('searchStrategy')}
                >
                  {SearchStrategy.map((k) => (
                    <MenuItem value={k}>{k}</MenuItem>
                  ))}
                </Select>
              </FormControl>
              <TextField
                value={globalConfiguration['searchTimeLimit'] ?? ''}
                onChange={updateGlobalConfiguration('searchTimeLimit')}
                required
                label="Search Time Limit"
                type="number"
              />
              <TextField
                value={globalConfiguration['searchThreshold'] ?? ''}
                onChange={updateGlobalConfiguration('searchThreshold')}
                required
                label="Search Threshold"
                type="number"
              />
              <TextField
                value={globalConfiguration['searchStepLimit'] ?? ''}
                onChange={updateGlobalConfiguration('searchStepLimit')}
                required
                label="Search Step Limit"
                type="number"
              />
            </>
          )}
        </div>
        <Button onClick={submitInput} variant="contained" color="primary">
          生成结果
        </Button>
      </div>
    </div>
  );
}

export default Configuration;
